package com.XZDP.Thread;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.XZDP.entity.RedisData;
import com.XZDP.entity.Shop;
import com.XZDP.utils.MyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;

@Slf4j
public class ShopMegThread extends Thread {
    private StringRedisTemplate redisTemplate;
    private MyUtils myUtils;
    private Shop shop;
    private Long id;

    public ShopMegThread(StringRedisTemplate redisTemplate, Shop shop, MyUtils myUtils, Long id) {
        this.redisTemplate = redisTemplate;
        this.shop = shop;
        this.myUtils = myUtils;
        this.id = id;
    }

    @Override
    public void run() {
        try {
            //进行缓存重建
            RedisData redisData = new RedisData();
            redisData.setData(shop);
            redisData.setExpired(System.currentTimeMillis() + 30 * 60 * 1000);
            // 创建ObjectMapper对象
            ObjectMapper objectMapper = new ObjectMapper();
            // 将对象转换为JSON字符串
            String json = null;
            json = objectMapper.writeValueAsString(redisData);
            redisTemplate.opsForValue().set("shop:" + id, json);
            log.info("缓存重建成功");
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        } finally {
            myUtils.CloseLock("Lock:shop");
        }
    }
}
